# -*- coding: utf-8 -*-
from gevent import monkey
# monkey.patch_all()

from api import api
from base64 import b64encode
from config import DEBUG
from flask import Flask
from gevent.wsgi import WSGIServer
from uuid import uuid4
from flask.ext.login import LoginManager
from flask import render_template, url_for
from model.user import User

app = Flask(__name__)
app.secret_key = b64encode(uuid4().hex)
app.debug = DEBUG
app.register_blueprint(api, url_prefix='/api')

login_manager = LoginManager()
login_manager.init_app(app)

# @login_manager.user_loader
# def load_user(userId):
#     print('hehehe')
#     return User.get({User.Field._id: userId})


@login_manager.request_loader
def load_user_from_request(request):
    token = request.headers.get('token')
    print('hhhhhhhhhhhhhhhhhhhhhh')
    if token:
        return User.get({User.Field._id: token})
    print('hahahhaha')
    return None

# For health test
@app.route('/')
def index():
    return render_template('root.html',
                            loginUrl = url_for("api.tlogin"),
                            title='Root');

if DEBUG:
    from werkzeug.serving import run_with_reloader
    from config import DEBUG_IP, DEBUG_PORT
    
    @run_with_reloader
    def run_server():
        http_server = WSGIServer((DEBUG_IP, DEBUG_PORT), app)
        http_server.serve_forever()
else:
    from config import NONDEBUG_IP, NONDEBUG_PORT
    http_server = WSGIServer((NONDEBUG_IP, NONDEBUG_PORT), app)
    http_server.serve_forever()
